package dingtalk

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
)

var (
	DingTalkToken = "f24c01294b56ff84bc77c43e47a52e3914073814c0edb3ab0b0bd232bca51937"
	DUrl          = "https://oapi.dingtalk.com/robot/send"
)

type DingTalkResponse struct {
	ErrorCode    int    `json:"errcode"`
	ErrorMessage string `json:"errmsg"`
}

type TextStrut struct {
	Content string `json:"content"`
}

type Message struct {
	MsgType string    `json:"msgtype"`
	Text    TextStrut `json:"text"`
}

func PostDingTalkRobot(message, baseURL, accessToken string) ([]byte, error) {
	if len(accessToken) < 1 {
		accessToken = DingTalkToken
	}
	if len(baseURL) < 1 {
		baseURL = DUrl
	}

	// Construct the full URL
	params := url.Values{}
	params.Add("access_token", accessToken)
	fullURL := baseURL + "?" + params.Encode()

	// Create the message payload
	msg := Message{
		MsgType: "text",
		Text: TextStrut{
			Content: message,
		},
	}

	// Serialize the message into JSON
	jsonData, err := json.Marshal(msg)
	if err != nil {
		return nil, fmt.Errorf("error marshalling JSON: %w", err)
	}

	// Create an HTTP POST request
	req, err := http.NewRequest("POST", fullURL, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, fmt.Errorf("error creating request: %w", err)
	}
	req.Header.Set("Content-Type", "application/json")

	// Send the request using an HTTP client
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("error sending request: %w", err)
	}
	defer resp.Body.Close()

	// Check for non-200 status codes
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("request failed with status code %d", resp.StatusCode)
	}

	// Read the response body
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("error reading response body: %w", err)
	}

	return body, nil
}
